package lanbo.cj.lmp.activity;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

import android.nfc.Tag;
import android.os.Debug;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import cn.bmob.v3.BmobQuery;
import lanbo.cj.lmp.BaseApplication;
import lanbo.cj.lmp.Config;
import lanbo.cj.lmp.R;
import lanbo.cj.lmp.bean.Asset;
import lanbo.cj.lmp.bean.Operation;
import lanbo.cj.lmp.bean.Record;
import lanbo.cj.lmp.utils.LocalData;
import lanbo.cj.lmp.view.DialogTips;
import lanbo.cj.lmp.view.FinishAdapter;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcA;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class FinishActivity extends Activity {
	private Button sure_finish_bt;
	private ListView finish_lv;
	private TextView assertText;
	private Map curMap;
	private String operationName,assertName;
	private Map<String, Object> finIteams ;
	private ArrayList<Map<String, Object>> findata;
	private NfcAdapter nfcAdapter;
	private PendingIntent pendingIntent;
	private IntentFilter[] mFilters;
	private String[][] mTechLists;
	private boolean isFinish;
	private String curRecord;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_finish);
		findbyid();
		setonlistener();
	}
	
	private void findbyid(){
		isFinish = false;
		curRecord = null;
		curMap = new HashMap<>();
		operationName = getIntent().getStringExtra("operaName");
		assertName = getIntent().getStringExtra("assertName");
		curRecord =  getIntent().getStringExtra("record");
		sure_finish_bt = (Button)findViewById(R.id.bt_finish);
		finish_lv = (ListView)findViewById(R.id.finish_iteams);
		assertText = (TextView)findViewById(R.id.assertName);
		assertText.setText(operationName);
		nfcAdapter = NfcAdapter.getDefaultAdapter(this);
		pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
				getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
		IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
		ndef.addCategory("*/*");
		mFilters = new IntentFilter[] { ndef };// 过滤器
		mTechLists = new String[][] {
				new String[] { MifareClassic.class.getName() },
				new String[] { NfcA.class.getName() } };// 允许扫描的标签类型
		getAssertData();
		
	}
	private void setonlistener(){
		
		sure_finish_bt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				isFinish = true;
				final DialogTips dialog = new DialogTips(FinishActivity.this,"请再次扫描tag以确认结束服务(放置标签上至少3秒，不然容易扫描失败)","取消");
				dialog.SetOnSuccessListener(new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialogInterface, int userId) {
						dialog.dismiss();
						isFinish = false;
					}
				});
				// 显示确认对话框
				dialog.show();
			}
		});
		
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		nfcAdapter.enableForegroundDispatch(this, pendingIntent, mFilters,
				mTechLists);
		if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())) {
			Toast.makeText(FinishActivity.this, "读取成功,在OnResume中", Toast.LENGTH_SHORT).show();
		}
	}
	
	
	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		if (isFinish&&NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
			String result = processIntent(intent);
			Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
			if(result!=null&&assertName.equals(readTagName(result))){
				curMap.put(Config.Tag_state,Config.STATE_NOT_USE);
				BaseApplication.getInstance().writeTag(curMap,tag);
				Toast.makeText(FinishActivity.this, "成功结束服务", Toast.LENGTH_SHORT).show();
				updateRecord(curRecord);
//				updateAssetState(assertName);
				finish();
			}else {
				DialogTips finish_failDialog= new DialogTips(FinishActivity.this, "读取错误，确认标签是否与原服务一致，再重扫tag", "确定");
				finish_failDialog.show();
			}
		}
	}
	/**
	 * 获取tab标签中的内容
	 */
	@SuppressLint("NewApi")
	private String readTagName(String res){
		Gson gson = new Gson();
		String tagName = null;
		try {
			Map<String, Object> map = gson.fromJson(res,
					new TypeToken<Map<String, Object>>() {
					}.getType());
			 tagName =(String) map.get(Config.Tag_name);
			curMap = map;
		} catch (Exception e) {
			Toast.makeText(FinishActivity.this, "Tag格式不正确", Toast.LENGTH_SHORT)
			.show();
			tagName = "读取错误";
		}
		return tagName;
	}
	private String processIntent(Intent intent) {
		Parcelable[] rawmsgs = intent
				.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
		if (rawmsgs ==null) return null;
		NdefMessage msg = (NdefMessage) rawmsgs[0];
		NdefRecord[] records = msg.getRecords();
		String resultStr = new String(records[0].getPayload());
		return resultStr;
	}

	/**
	 * 从bmob云端获取operation的操作步骤，用finishAdapter写在列表中
	 * 
	 * */
	private void getAssertData(){
		findata = new ArrayList<Map<String,Object>>();
		
		BmobQuery<Operation> query = new BmobQuery<Operation>();
//		query.addWhereEqualTo("operationName", operationName);
//		query.findObjects(FinishActivity.this, new FindListener<Operation>() {
//
//			@Override
//			public void onSuccess(List<Operation> arg0) {
//				// TODO Auto-generated method stub
//				ArrayList<String> ope_item = arg0.get(0).getOperationSteps();
//				for (int i = 0; i < ope_item.size(); i++) {
//					finIteams = new HashMap<String, Object>();
//					finIteams.put("buzhou", ope_item.get(i));
//					findata.add(finIteams);
//				}
//				System.out.print(ope_item);
//				FinishAdapter finishAdapter = new FinishAdapter(FinishActivity.this,findata);
//
//				finish_lv.setAdapter(finishAdapter);
//			}
//
//			@Override
//			public void onError(int arg0, String arg1) {
//				// TODO Auto-generated method stub
//				Toast.makeText(FinishActivity.this, "获取步骤失败，请检测网络", Toast.LENGTH_LONG).show();
//			}
//		});

		/*
		*因暂无详细步骤暂时写死
		* */
		query.getObject(FinishActivity.this, "73878c3455", new GetListener<Operation>() {

			@Override
			public void onFailure(int arg0, String arg1) {
				// TODO Auto-generated method stub
				finIteams = new HashMap<String, Object>();
				finIteams.put("buzhou","步骤一");
				findata.add(finIteams);
				finIteams = new HashMap<String, Object>();
				finIteams.put("buzhou","步骤二");
				findata.add(finIteams);

				FinishAdapter finishAdapter = new FinishAdapter(FinishActivity.this,findata);

				finish_lv.setAdapter(finishAdapter);
			}

			@Override
			public void onSuccess(Operation arg0) {
				// TODO Auto-generated method stub
				ArrayList<String> ope_item = arg0.getOperationSteps();
				for (int i = 0; i < ope_item.size(); i++) {
					finIteams = new HashMap<String, Object>();
					finIteams.put("buzhou", ope_item.get(i));
					findata.add(finIteams);
				}
				FinishAdapter finishAdapter = new FinishAdapter(FinishActivity.this,findata);

				finish_lv.setAdapter(finishAdapter);
			}
		});

	}
	private void updateRecord(String recordID){

		final Record record = new Record();
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		record.setEndTime(sdf.format(date));
		if (recordID == null||recordID.isEmpty()){
			record.setOperationType(operationName);
			record.setCustId(BmobUser.getCurrentUser(FinishActivity.this).getObjectId());
			record.save(this, new SaveListener() {
				@Override
				public void onSuccess() {

				}

				@Override
				public void onFailure(int i, String s) {
					LocalData localData = new LocalData();
					localData.saveData(record);
				}
			});
		}
		record.update(this,recordID ,new UpdateListener() {
			@Override
			public void onSuccess() {


			}

			@Override
			public void onFailure(int i, String s) {
				LocalData localData = new LocalData();
				localData.saveData(record);
			}
		});
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == event.KEYCODE_BACK){
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}
}
